//
//  AppListViewController.m
//  LimitFree
//
//  Created by LZXuan on 15-6-8.
//  Copyright (c) 2015年 轩哥. All rights reserved.
//

#import "AppListViewController.h"
#import "AFNetworking.h"
#import "AppModel.h"
#import "AppCell.h"
#import "JHRefresh.h"
#import "DetailViewController.h"
#import "SettingsViewController.h"
#import "CategoryViewController.h"
#import "SearchViewController.h"




@interface AppListViewController ()

@end

@implementation AppListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //导航条背景
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"navigationbar"] forBarMetrics:UIBarMetricsDefault];
    //设置导航基本内容
    [self addTitleViewWithTitle:self.title];
    [self addItemWithTitle:@"分类" target:self action:@selector(leftClick:) isLeft:YES];
    [self addItemWithTitle:@"设置" target:self action:@selector(rightClick:) isLeft:NO];
    
    [self creatTableView];
    
    //创建af
    _manager = [AFHTTPRequestOperationManager manager];
    //响应格式 二进制 不解析
    _manager.responseSerializer  = [AFHTTPResponseSerializer serializer];
}

#pragma mark - tableView
- (void)creatTableView {
    self.dataArr = [[NSMutableArray alloc] init];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-64-49) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 100;
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"AppCell" bundle:nil] forCellReuseIdentifier:@"AppCell"];
    [self.view addSubview:self.tableView];
    
    //在tableView上 添加一个 头视图 searchBar
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 44)];
    //设置代理 searchBar 委托代理处理事件
    searchBar.delegate = self;
    //提示语
    searchBar.placeholder = @"60万应用等你搜搜看";
    
    self.tableView.tableHeaderView = searchBar;
}
#pragma mark - UISearchBarDelegate
//将要开始进入编辑模式的时候调用
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    //显示 cancel 按钮
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}
//结束编辑模式调用
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    //隐藏 cancel
    [searchBar setShowsCancelButton:NO animated:YES];
    return YES;
}
//点击cancel 按钮调用
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    //收键盘
    [searchBar resignFirstResponder];
    //把searchBar的内容 清空
    searchBar.text = @"";
}
//点击 search 按钮的时候调用
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [searchBar resignFirstResponder];
    NSString *url = nil;
    if ([self.category isEqualToString:kLimitType]) {
        url = SEARCH_LIMIT_URL;
    }else if ([self.category isEqualToString:kReduceType]){
        url = SEARCH_REDUCE_URL;
    }else if ([self.category isEqualToString:kFreeType]){
        url = SEARCH_FREE_URL;
    }else {
        url = SEARCH_HOT_URL;
    }
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    
    //传值
    searchVC.searchWord = searchBar.text;
    searchVC.url = url;
    
    searchVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:searchVC animated:YES];
}


#pragma mark - tableView协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AppCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AppCell" forIndexPath:indexPath];
    AppModel *model = self.dataArr[indexPath.row];
    //传分类
    cell.category = self.category;
    //填充cell
    [cell showDataWithModel:model indexPath:indexPath];
    return cell;
}

#pragma mark - 选中cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    AppModel *model = _dataArr[indexPath.row];
    //界面跳转
    //创建 xib 中的视图控制器
    DetailViewController *detail = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    //传值
    detail.applicationId = model.applicationId;
    detail.category = self.category;
    [self.navigationController pushViewController:detail animated:YES];
}



#pragma mark - 如果不满足子类 那么子类要重写

//
//第一次下载
- (void)firstDownload {//在子类调用
    self.currentPage = 1;
    self.isRefreshing = NO;
    self.isLoadMoring = NO;
    self.categoryId = @"0";
    //下载数据
    [self addTaskUrl:self.requestUrl isRefresh:NO];//第一次 不刷新
}
//增加下载任务
- (void)addTaskUrl:(NSString *)url isRefresh:(BOOL)isRefresh {
    //设置 类型
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleDrop];
    //设置状态
    [MMProgressHUD showWithTitle:@"数据下载" status:@"loading...."];
    
    
    if ([self.category isEqualToString:kHotType]) {
        //热榜接口和其他接口处理不一样
        url = [NSString stringWithFormat:url,self.currentPage];
    }else{
        url = [NSString stringWithFormat:url,self.currentPage,self.categoryId];
    }
    
    //判断 这次下载是走本地缓存还是网络下载
    //走本地 缓存
    /*
     满足条件1.不是刷新 2.有缓存文件 3.缓存文件没有超时
     */
    //检测缓存文件是否存在--》通过文件全路径 检测文件是否存在
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:[LZXHelper getFullPathWithMyCacheFile:url]];
    //检测文件是否超时 允许超时 1小时
    BOOL isTimeOut = [LZXHelper isTimeOutFile:url time:60*60];
    
    if (isRefresh == NO&&isExist == YES&&isTimeOut == NO) {
        //走本地缓存
        NSData *data = [NSData dataWithContentsOfFile:[LZXHelper getFullPathWithMyCacheFile:url]];
        //data 就是一个之前保存的json数据
        //解析
        //解析json
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = dict[@"applications"];
        
        //只缓存了第一页
        [self.dataArr removeAllObjects];
        //遍历数组解析
        for (NSDictionary *appDict in arr) {
            AppModel *model = [[AppModel alloc] init];
            //kvc 赋值
            [model setValuesForKeysWithDictionary:appDict];
            [self.dataArr addObject:model];
        }
        //刷新表格
        [self.tableView reloadData];
        NSLog(@"本地下载");
        
        [MMProgressHUD dismissWithSuccess:@"恭喜你" title:@"本地下载成功"];
        
        return;//返回 不走网络了
    }
    /*********************************/
    
    __weak typeof (self) weakSelf = self;
    //开始下载
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"下载成功");
        if (responseObject) {
            if (weakSelf.currentPage == 1) {
                [weakSelf.dataArr removeAllObjects];
                //下面我们做一下 第一页的缓存(下载数据之后 把数据保存到本地，如果下次再加载第一页数据的时候满足条件可以去加载本地的缓存数据-》这样 用户在离线情况下也可以浏览第一页(数据未超时))
                //第一页在这里网络下载完成 保存到本地
                NSData *data = (NSData *)responseObject;
                //获取 缓存路径->把一个url 内部进行md5加密得到一个新的字符串 作为文件名 返回文件名的全路径
                NSString *filePath = [LZXHelper getFullPathWithMyCacheFile:url];
                
                //把二进制数据写到本地
                [data writeToFile:filePath atomically:YES];
                
            }
            
            //解析json
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr = dict[@"applications"];
            //遍历数组解析
            for (NSDictionary *appDict in arr) {
                AppModel *model = [[AppModel alloc] init];
                //kvc 赋值
                [model setValuesForKeysWithDictionary:appDict];
                [weakSelf.dataArr addObject:model];
            }
            //刷新表格
            [weakSelf.tableView reloadData];
            [weakSelf endRefreshing];
            
        }
        //关闭下载进度框
        [MMProgressHUD dismissWithSuccess:@"恭喜你" title:@"下载成功"];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
        //结束刷新
        [weakSelf endRefreshing];
        
        //下载失败也要关闭进度
        [MMProgressHUD dismissWithError:@"下载失败" title:@"警告"];
        
    }];
}
#pragma mark - 刷新
//刷新
- (void)creatRefreshView {//在子类中调用 如果不适合子类那么重写
    __weak typeof(self) weakSelf = self;
    
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.currentPage = 1;
        weakSelf.isRefreshing = YES;
        
        [weakSelf addTaskUrl:weakSelf.requestUrl isRefresh:YES];
    }];

    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //上拉加载更多
        if (weakSelf.isLoadMoring) {
            return ;
        }
        weakSelf.isLoadMoring = YES;
        weakSelf.currentPage++;
        [weakSelf addTaskUrl:weakSelf.requestUrl isRefresh:YES];
        
    }];
    
    
}
//结束刷新
- (void)endRefreshing {
    if (self.isRefreshing) {
        self.isRefreshing = NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }
    if (self.isLoadMoring) {
        self.isLoadMoring = NO;
        [self.tableView footerEndRefreshing];
    }
}



#pragma mark - 左右按钮
- (void)leftClick:(UIButton *)button {
    CategoryViewController *category = [[CategoryViewController alloc] init];
    
    //把分类 的类型传过去
    category.categrory = self.category;
    
    //传入block-->根据 最新的categoryId 下载新数据
    __weak typeof(self)weakSelf = self;
    [category setMyBlock:^(NSString *categoryId) {
        weakSelf.currentPage = 1;
        weakSelf.categoryId = categoryId;
        //重新下载数据
        [weakSelf addTaskUrl:weakSelf.requestUrl isRefresh:YES];
        //让tableView的cell 滚动到第0行
        [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
    }];
    
    category.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:category animated:YES];
}
- (void)rightClick:(UIButton *)button {
    SettingsViewController *settings = [[SettingsViewController alloc] init];
    [self.navigationController pushViewController:settings animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
